using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

namespace ACM.cmsarea08.Controls
{
    /// <summary>
    /// Handler che recupera l'img captcha dalla cache o dalla sessione, per poterlo utilizzare necessita che venga dichiarato
    /// l'hadler nel web.config:
    /// <httpHandlers>
    ///     <add verb="GET" path="CaptchaLoader.ashx" type="ACM.cmsarea08.Controls.CaptchaHandler, cms08_controls" />
    /// </httpHandlers>
    /// </summary>
    public class CaptchaHandler : System.Web.IHttpHandler
    {
        public void ProcessRequest(System.Web.HttpContext contesto)
        {
            HttpApplication app = contesto.ApplicationInstance;
            string _unico = app.Request.QueryString["guid"].ToString();
            //creo istanza di captcha image.
            //
            CaptchaImage ci=null;

            if(_unico.Trim()!="") {
                if(string.IsNullOrEmpty(app.Request.QueryString["s"]))
                    ci = (CaptchaImage) HttpRuntime.Cache.Get(_unico);
                else
                    ci = (CaptchaImage)HttpContext.Current.Session[_unico];
            }

            if(ci==null)  {
                app.Response.StatusCode = 404;
                contesto.ApplicationInstance.CompleteRequest();
                return;
            }
            //se ottengo l'img indietro
            Bitmap b = ci.GetImage() ; //ci.RenderImage;
            b.Save(app.Context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            b.Dispose();
            app.Response.ContentType = "image/jpeg";
            app.Response.StatusCode = 200;
            contesto.ApplicationInstance.CompleteRequest();

        }

        public bool IsReusable
        {
            get { return true; }
        }

    }
}
